<?php
include 'mysql.inc.php';

session_start();
$userid = $_SESSION['user'];
if(!isset($userid)) exit;


query('BEGIN');
query('SET AUTOCOMIIT=0');

try {
	$sql = "select * from `user` where id='{$userid}' for update";
	$rs = query($sql);
	$user = fetch_one($rs);
	
	if (!$user){
		query('COMMIT');
		query('SET AUTOCOMMIT=1');
		closeConnection();
		exit;
	}
	if ($user['rank'] > 0) {
		
		$choice = $user['choice'];
		if ($choice >0) {
			$choice = $choice - 1;
		}
		
		$sql = "update `user` set `choice`='{$choice}' where id='{$userid}'";
		query($sql);
		$result = array("res" => 'success', "choice" => $choice, "datas" => [1, 2, 3]);
		echo json_encode($result);
	} else {
		if ($user['choice'] < 1) {
			$result = array("res" => 'nochoice', "choice" => 0, "datas" => [1, 2, 3]);
			echo json_encode($result);
		} else {
			$sql = "update `user` set `choice`=`choice` + 1 where id='{$userid}'";
			query($sql);
			
			$sql = "select * `user` set `choice`=`choice` + 1 where id='{$userid}'";
		}
	}
	query('COMMIT');
} catch(Exception $e) {
	query('ROLLBACK');
	echo $e;
}
query('SET AUTOCOMMIT=1');
closeConnection();







$id = $_POST['id'];
$cookie = $_COOKIE["vote"];
if (isset($cookie)) {
	$result = array("res" => 'exist');
	echo json_encode($result);
	exit;
}
if (!isset($id)) {
	$result = array("res" => 'error');
	echo json_encode($result);
	exit;
}
$sql = "select * from `star` where id='{$id}'";
$rs = query($sql);
$star = fetch_one($rs);

if(!$star) {
	$result = array("res" => 'error');
	echo json_encode($result);
	exit;
}

query('BEGIN');
query('SET AUTOCOMIIT=0');
try {
	$sql = "SELECT * FROM `star` WHERE id='{$id}' FOR UPDATE";
	$rs = query($sql);
	$row = fetch_one($rs);
	
	$sql = "update `star` set `vote`=`vote` + 1 where id='{$id}'";
	query($sql);
	query('COMMIT');
} catch(Exception $e) {
	query('ROLLBACK');
	echo $e;
}
query('SET AUTOCOMMIT=1');

$sql = "select * from `star` order by id";
$rs = query($sql);
$datas = mysql_fetch_assoc($rs);



$sql = "select sum(vote) as v from `star`";
$rs = query($sql);
$row = fetch_one($rs);
$total = $row['v'];

$result = array("res" => 'success', "total" => $total, "datas" => $datas);
echo json_encode($result);
closeConnection();
?>